﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.Collections.Specialized;
using System.IO;

namespace ConfigBuilder
{
    /// <summary>
    /// ConfigTemplateBuilder
    /// 
    /// 配置文件模版生成类
    /// </summary>
    public class ConfigBuilder
    {
        /// <summary>
        /// 模版路径
        /// </summary>
        public string TemplatePath = string.Empty;

        /// <summary>
        /// 应用程序配置文件路径
        /// </summary>
        public string MissionPath = string.Empty;

        /// <summary>
        /// 机器token
        /// </summary>
        public Guid MachineGuid = new Guid();

        /// <summary>
        /// 应用程序token
        /// </summary>
        public string MissionToken = string.Empty;

        /// <summary>
        /// 帐户服务端URI
        /// </summary>
        public Uri AccountServiceUri = null;

        /// <summary>
        /// POST Content
        /// </summary>
        public string PostContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body><FetchAccountsByMachineToken xmlns=\"http://tempuri.org/\"><machineToken><MachineGuid>{0}</MachineGuid><MissionToken>{1}</MissionToken></machineToken></FetchAccountsByMachineToken></soap12:Body></soap12:Envelope>";

        /// <summary>
        /// 根据MachineToken来生成外挂配置文件
        /// </summary>
        /// <param name="token">唯一标识应用程序的token</param>
        /// <returns>是否成功</returns>
        /// <returns></returns>
        public bool Build()
        {
            bool result = false;

            if (string.IsNullOrEmpty(TemplatePath) || string.IsNullOrEmpty(MissionPath) || MachineGuid == new Guid() || string.IsNullOrEmpty(MissionToken) || AccountServiceUri == null)
            {
                throw new Exception("TemplatePath,MissionPath,MachineGuid,MissionToken,AccountServiceUri can not be null");
            }

            XmlDocument xd = new XmlDocument();
            xd.Load(TemplatePath);                              //加载模版
            XmlNode xnAccounts = xd.SelectSingleNode("Root/Accounts");
            xnAccounts.RemoveAll();                                     //移除帐号信息
            
            XmlDocument accounts = GetAccounts();               //根据MachineToken获取帐号

            int count = 0;

            XmlNodeList xnl = accounts.GetElementsByTagName("MetinAccount");

            if (xnl == null || xnl.Count == 0)
            {
                throw new Exception("根据MachineToken没有获取到帐户数据");
            }
            else
            {
                count = xnl.Count;
            }
            
            XmlNodeList accountName = accounts.GetElementsByTagName("AccountName");
            XmlNodeList accountPwd = accounts.GetElementsByTagName("Password");
            XmlNodeList accountServer = accounts.GetElementsByTagName("Name");
            XmlNode xnSetting = xd.SelectSingleNode("Root/Setting");

            XmlNode xn;
            for (int i = 0; i < count; i++)      //依次添加服务器信息
            {
                xn = xd.CreateElement(accountName[i].InnerText);
                XmlAttribute xa = xd.CreateAttribute("Password");
                xa.Value = accountPwd[1].InnerText;
                xn.Attributes.Append(xa);           //添加密码
                xa = xd.CreateAttribute("Server");
                xa.Value = accountServer[i].InnerText;
                xn.Attributes.Append(xa);           //添加服务器信息
                if(xnSetting != null)
                    xn.AppendChild(xnSetting.Clone());
                xnAccounts.AppendChild(xn);
            }

            xn = xd.SelectSingleNode("Root/LastAccount");       //移除LastAccount
            if (xn != null)
                xd.DocumentElement.RemoveChild(xn);

            xd.Save(MissionPath);

            return result;
        }

        /// <summary>
        /// 从帐号服务端获取数据
        /// </summary>
        /// <returns>返回xml文档</returns>
        public XmlDocument GetAccounts()
        {
            HttpWebRequest request = WebRequest.Create(AccountServiceUri) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/soap+xml; charset=utf-8";

            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(string.Format(PostContent, MachineGuid, MissionToken));
            writer.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string xml = reader.ReadToEnd();
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(xml);

            return xd;
        }
    }
}
